<template>
  <el-dialog
    v-model="visibleAlter"
    width="1160"
    align-center
    center
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="change-list-wrap" v-loading="loading">
      <!-- 新的sku -->
      <p class="f18 mb20">商品价格调整后数据</p>
      <el-table border :data="newList" style="width: 100%; height: 300px" :row-class-name="setAddClass">
        <el-table-column property="skuId" fixed="left" label="编码" width="200">
          <template #default="scope">
            <span>{{ scope.row.code }}</span>
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in skuColsNew" :label="item.split('-')[0]" :key="index">
          <template #default="scope">
            <img
              v-show="item.split('-')[1] === '3'"
              :src="scope.row.statsText || scope.row.picUrl"
              alt=""
              style="width: 80px; height: 80px; object-fit: cover; vertical-align: middle"
            />
            {{ scope.row[item.split("-")[0]] }}
          </template>
        </el-table-column>
        <el-table-column property="productUnit" label="单位" width="80">
          <template #default="scope">
            <span>{{ getUnitLabel(String(scope.row.productUnit)) }}</span>
          </template>
        </el-table-column>
        <el-table-column property="factoryStock" label="库存" width="200"></el-table-column>
        <el-table-column property="factoryPrice" label="正价" width="200"></el-table-column>
        <el-table-column property="factoryPreferentialPrice" label="特价" width="200"></el-table-column>
        <el-table-column fixed="right" label="状态" width="80">
          <template #default="scope">
            <span>{{ scope.row.listingStatus === 1 ? "上架" : "下架" }}</span>
            <!-- <el-switch
              v-show="scope.row.skuStatus === 0"
              v-model="scope.row.skuStatus"
              active-text="重新启用"
              :active-value="1"
              :inactive-value="0"
            />
            <div v-show="scope.row.skuStatus === 1" style="display: flex; align-items: center">
              <el-radio-group
                v-model="scope.row.listingStatus"
                @change="
                  val => {
                    radioChange(val, scope.row);
                  }
                "
              >
                <el-radio :label="1" :value="1">上架</el-radio>
                <el-radio :label="-1" :value="-1">下架</el-radio>
              </el-radio-group>
              <el-button type="danger" class="ml10" link @click="changeSkuStatus(scope.row, 0)">禁用</el-button>
            </div> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 旧的sku -->
      <p class="f18 mb20 mt40">商品价格调整前数据</p>
      <el-table border :data="oldList" style="width: 100%; height: 300px">
        <el-table-column property="skuId" fixed="left" label="编码" width="200">
          <template #default="scope">
            <span>{{ scope.row.code }}</span>
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in skuColsOld" :label="item.split('-')[0]" :key="index">
          <template #default="scope">
            <img
              v-show="item.split('-')[1] === '3'"
              :src="scope.row.statsText || scope.row.picUrl"
              alt=""
              style="width: 80px; height: 80px; object-fit: cover; vertical-align: middle"
            />
            {{ scope.row[item.split("-")[0]] }}
          </template>
        </el-table-column>
        <el-table-column property="productUnit" label="单位" width="80">
          <template #default="scope">
            <span>{{ getUnitLabel(String(scope.row.productUnit)) }}</span>
          </template>
        </el-table-column>
        <el-table-column property="factoryStock" label="库存" width="200"></el-table-column>
        <el-table-column property="factoryPrice" label="正价" width="200"></el-table-column>
        <el-table-column property="factoryPreferentialPrice" label="特价" width="200"></el-table-column>
        <el-table-column fixed="right" label="状态" width="80">
          <template #default="scope">
            <span>{{ scope.row.listingStatus === 1 ? "上架" : "下架" }}</span>
            <!-- <el-switch
              v-show="scope.row.skuStatus === 0"
              v-model="scope.row.skuStatus"
              active-text="重新启用"
              :active-value="1"
              :inactive-value="0"
            />
            <div v-show="scope.row.skuStatus === 1" style="display: flex; align-items: center">
              <el-radio-group
                v-model="scope.row.listingStatus"
                @change="
                  val => {
                    radioChange(val, scope.row);
                  }
                "
              >
                <el-radio :label="1" :value="1">上架</el-radio>
                <el-radio :label="-1" :value="-1">下架</el-radio>
              </el-radio-group>
              <el-button type="danger" class="ml10" link @click="changeSkuStatus(scope.row, 0)">禁用</el-button>
            </div> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- <el-tabs v-model="activeName" class="demo-tabs" type="card">
        <el-tab-pane label="数据对比" name="1">
          <div class="tabs1">
            <div class="left-header">
              <div class="sku">SKU编码</div>

              <div v-for="item in skuCols" :key="item">
                {{ item.split("-")[0] }}
              </div>

              <div class="unit">单位</div>
              <div class="contrast-price">价格前后</div>
              <div class="stock">库存</div>
              <div class="normal-price">正价</div>
              <div class="spe-price">特价</div>
              <div class="action" style="line-height: 32px">状态</div>
            </div>
            <div class="right-header">
              <div style="display: flex">
                <div class="list-item" v-for="(item, index) in newList" :key="index">
                  <div class="sku pd20" :title="item.skuId">{{ item.skuId }}</div>
                  <div class="pd20" v-for="_item in skuCols" :key="_item">
                    <img
                      v-show="_item.split('-')[1] === '3'"
                      :src="item.statsText || item.picUrl"
                      alt=""
                      style="width: 80px; height: 80px; object-fit: cover; vertical-align: middle"
                    />
                    {{ item[_item.split("-")[0]] }}
                  </div>
                  <div class="pd20">{{ getUnitLabel(String(item.productUnit)) }}</div>
                  <div class="contrast-price">
                    <div class="old-val">调整前</div>
                    <div class="new-val">调整后</div>
                  </div>
                  <div class="stock contrast-val">
                    <div class="old-val">{{ oldList[index].factoryStock }}</div>
                    <div class="new-val">{{ item.factoryStock }}</div>
                  </div>
                  <div class="normal-price contrast-val">
                    <div class="old-val">{{ getOldVal(item, "factoryPrice") }}</div>
                    <div class="new-val">{{ item.factoryPrice || "-" }}</div>
                  </div>
                  <div class="spe-price contrast-val">
                    <div class="old-val">{{ getOldVal(item, "factoryPreferentialPrice") }}</div>
                    <div class="new-val">{{ item.factoryPreferentialPrice || "-" }}</div>
                  </div>
                  <div class="action pd20">
                    <span style="line-height: 32px">{{ item.listingStatus === 1 ? "上架" : "下架" }}</span>
                    <el-switch
                      v-show="item.skuStatus === 0"
                      v-model="item.skuStatus"
                      active-text="重新启用"
                      :active-value="1"
                      :inactive-value="0"
                    />
                    <div v-show="item.skuStatus === 1" style="display: flex; align-items: center">
                      <el-radio-group
                        v-model="item.listingStatus"
                        @change="
                          val => {
                            radioChange(val, item);
                          }
                        "
                      >
                        <el-radio :label="1" :value="1">上架</el-radio>
                        <el-radio :label="-1" :value="-1">下架</el-radio>
                      </el-radio-group>
                      <el-button type="danger" link @click="changeSkuStatus(item, 0)">禁用</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="新增数据" name="2">
          <el-table border :data="addList" style="width: 100%; height: 300px">
            <el-table-column property="skuId" label="编码" width="200">
              <template #default="scope">
                <span>{{ scope.row.skuId }}</span>
              </template>
            </el-table-column>
            <el-table-column v-for="(item, index) in skuCols" :label="item.split('-')[0]" :key="index">
              <template #default="scope">
                <img
                  v-show="item.split('-')[1] === '3'"
                  :src="scope.row.statsText || scope.row.picUrl"
                  alt=""
                  style="width: 80px; height: 80px; object-fit: cover; vertical-align: middle"
                />
                {{ scope.row[item.split("-")[0]] }}
              </template>
            </el-table-column>
            <el-table-column property="productUnit" label="单位" width="80">
              <template #default="scope">
                <span>{{ getUnitLabel(String(scope.row.productUnit)) }}</span>
              </template>
            </el-table-column>
            <el-table-column property="factoryStock" label="库存" width="200"></el-table-column>
            <el-table-column property="factoryPrice" label="正价" width="200"></el-table-column>
            <el-table-column property="factoryPreferentialPrice" label="特价" width="200"></el-table-column>
            <el-table-column fixed="right" label="状态" width="80">
              <template #default="scope">
                <span>{{ scope.row.listingStatus === 1 ? "上架" : "下架" }}</span>
                <el-switch
                  v-show="scope.row.skuStatus === 0"
                  v-model="scope.row.skuStatus"
                  active-text="重新启用"
                  :active-value="1"
                  :inactive-value="0"
                />
                <div v-show="scope.row.skuStatus === 1" style="display: flex; align-items: center">
                  <el-radio-group
                    v-model="scope.row.listingStatus"
                    @change="
                      val => {
                        radioChange(val, scope.row);
                      }
                    "
                  >
                    <el-radio :label="1" :value="1">上架</el-radio>
                    <el-radio :label="-1" :value="-1">下架</el-radio>
                  </el-radio-group>
                  <el-button type="danger" class="ml10" link @click="changeSkuStatus(scope.row, 0)">禁用</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs> -->
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="clickClose">我知道了</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { getEnumAll, checkMerchantSku } from "@/apis/products/specifications";
import { ElMessage } from "element-plus";

const activeName = ref("1");
const visibleAlter = ref(false);
const _LIST = ref([]);
const addList = ref([]);
const newList = ref([]);
const oldList = ref([]);
const units = ref([]);
const loading = ref(false);

const emit = defineEmits(["close"]);
const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isShow: false,
        LIST: []
      };
    }
  }
});
watch(
  () => props.optionInfo,
  async val => {
    visibleAlter.value = val.isShow;
    _LIST.value = val.LIST;
    console.log("父组件传递的变更明细===", _LIST.value);

    if (val.isShow) {
      loading.value = true;
      await getEnumAllFun();
    }
    // let _addList = []; //新增的sku
    // let _newList = []; //变更价格后的sku
    // _LIST.value.rechangeSkuList.map(item => {
    //   if (item.linkSkuId) {
    //     _newList.push(item);
    //   } else {
    //     _addList.push(item);
    //   }
    // });

    if (_LIST.value.changeSkuList.length > 0) oldList.value = createSku([..._LIST.value.changeSkuList], "old", true);
    if (_LIST.value.rechangeSkuList.length > 0) newList.value = createSku([..._LIST.value.rechangeSkuList], "new", true);
    // if (_newList.length > 0) newList.value = createSku([..._newList], true);
    // if (_addList.length > 0) addList.value = createSku([..._addList], true);
    loading.value = false;
  },
  { deep: true }
);

onMounted(async () => {});

const getEnumAllFun = async () => {
  const _Enums = await getEnumAll(); //查询完整的数据字典

  //单位-shop_unit
  units.value = _Enums.data.filter(item => {
    if (item.dictType === "shop_unit") {
      return item;
    }
  })[0].dictDataList;
};

const getOldVal = (item, key) => {
  const oldObj = oldList.value.find(_item => _item.skuId === item.skuId);
  return oldObj ? oldObj[key] : "-";
};

const radioChange = (val, row) => {
  console.log("切换是否上架===", val, row, "skuId===", row.skuId);
  if (val === 1 && row.skuId) {
    // console.log("请求校验是否允许上架接口");
    checkMerchantSku({ skuId: row.skuId }).then(res => {
      console.log("sku收否允许上架校验结果===", res);
      if (res.data) {
        row.businessListingStatus = 1; //允许上架，状态为 1 已上架
      } else {
        row.businessListingStatus = -1; //不允许上架，状态改为 -1 下架
        ElMessage({
          message: res.msg || "该条sku不允许上架操作",
          type: "error"
        });
      }
    });
  }
};
const changeSkuStatus = row => {
  row.skuStatus = 0; //禁用
};

const skuColsOld = ref([]);
const skuColsNew = ref([]);
const createSku = (resSkuList, type, init) => {
  //   console.log("createSku skuList===", resSkuList);

  const { Arr: _skuList, Cols: _skuCols } = formatTableData(resSkuList);
  //   console.log("动态表头 2222222===", _skuCols, _skuList);
  let skuListSort = _skuList;
  if (init) {
    const SkuList = JSON.parse(JSON.stringify(_skuList));
    const keyOne = _skuCols[0].split("-")[0];
    skuListSort = SkuList.sort((a, b) => {
      if (a[keyOne] != b[keyOne]) {
        return String(a[keyOne]).localeCompare(String(b[keyOne]));
      }
    });
    // console.log("排序后的table===", skuListSort);
  }
  if (type === "new") {
    skuColsNew.value = _skuCols;
  } else if (type === "old") {
    skuColsOld.value = _skuCols;
  }
  return skuListSort;
};
//处理成el-table能渲染的数据
const formatTableData = list => {
  const Arr = [];
  let Cols = [];
  for (let item of list) {
    let obj = { ...item };
    Cols = [];
    // console.log("处理成el-table能渲染的数据222", obj);
    for (let _item of item.properties) {
      if (_item.img || _item?.statsText) {
        obj.picUrl = _item?.img || _item?.statsText;
        obj.statsText = _item?.statsText;
      }
      // obj[_item.specificationId] = _item.specificationName; //暂时去掉 id:name {111:颜色} 的转换
      obj[_item.specificationName] = _item.specificationVal; //转换成 {颜色:红色} {尺寸：M} {种类:沙发}
      if (!Cols.includes(_item.specificationName + "-" + _item.speType)) {
        Cols.push(_item.specificationName + "-" + _item.speType);
        // Cols.push(_item.specificationName);
      }
    }
    Arr.push(obj);
  }
  return { Arr, Cols };
};

const setAddClass = ({ row, rowIndex }) => {
  console.log(90909090, row, row.skuId, row.linkSkuId);
  if (row.skuId === row.linkSkuId) {
    console.log(11111);
    return "blue";
  } else {
    console.log(22222);
    return "";
  }
};

const getUnitLabel = value => {
  const obj = units.value.filter(item => {
    if (item.dictValue === value) {
      return item;
    }
  })[0];
  return obj?.dictLabel || "-";
};

const clickClose = () => {
  emit("close");
};
</script>

<style lang="scss" scoped>
:deep(.el-table__body tr.blue.hover-row > td.el-table__cell) {
  background-color: #409eff;
  color: white;
}
:deep(.el-table__row) {
  &.blue {
    background-color: #409eff;
    color: white;
  }
}
.change-list-wrap {
  .tabs1 {
    display: flex;
    .sku {
      background-color: #f2f6fc;
    }
    .action {
      border-bottom: 1px solid #e1e6ed;
      height: 72px;
      box-sizing: border-box;
      padding: 20px 10px !important;
      :deep(.el-radio) {
        margin-right: 16px;
      }
    }
    .size {
      display: flex;
    }
    .contrast-price,
    .contrast-val {
      display: flex;
      justify-content: space-between;
      & > div {
        flex: 1;
        padding: 20px;
        padding-right: 0;
        &.new-val {
          background-color: #f2f6fc;
          border-left: 1px solid #e1e6ed;
        }
      }
    }
    .left-header {
      width: 120px;
      box-shadow: 4px 0px 10px 0px rgba(1, 46, 100, 0.2);
      z-index: 2;
      .action {
        padding: 20px !important;
      }
      & > div {
        padding: 20px;
        border-top: 1px solid #e1e6ed;
        border-left: 1px solid #e1e6ed;
        border-right: 1px solid #e1e6ed;
        background-color: #f2f6fc;
      }
    }
    .right-header {
      flex: 1;
      overflow-x: auto;
      .list-item {
        width: 190px;
        border-right: 1px solid #e1e6ed;
        & > div {
          border-top: 1px solid #e1e6ed;
          white-space: nowrap; /* 确保文本在一行内显示 */
          overflow: hidden; /* 隐藏超出容器的文本 */
          text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
        }
      }
    }
  }
}
</style>
